package banco;

import org.hibernate.Session;
import org.hibernate.Transaction;

/**
 *  @netbeans.hibernate.facade beanClass=banco.Cliente
 */
public class ClienteFacade { 
    public void saveCliente(Cliente cliente) {
        Session session = banco.HibernateUtil.currentSession();
        Transaction tx = session.beginTransaction();
        session.save(cliente);
        tx.commit();
        banco.HibernateUtil.closeSession();
    }
    
    public int getMaxNumero() 
    {
        Session session = banco.HibernateUtil.currentSession();
        org.hibernate.Query query = session.createQuery(
                " select max(numero) from" +
                " Cliente as cliente ");
        
        Integer result = (Integer) query.uniqueResult();
        
        if (result == null) return 0;
        else return result.intValue();

    }
    
    public void insereCliente(String nome, int rg, int cpf)
    {
        Cliente cliente = new Cliente();
        
        cliente.setNome(nome);
        cliente.setCpf(cpf);
        cliente.setRg(rg);
        
        int ultimoNumero = getMaxNumero();
        
        cliente.setNumero(ultimoNumero+1);
        
        saveCliente(cliente);
    }

    
    public java.util.List listAll() {
        Session session = banco.HibernateUtil.currentSession();
        org.hibernate.Query query = session.createQuery(
                " select cliente " +
                " from  " +
                " Cliente as cliente " +
                " order by cliente.numero");
        
        return query.list();
    }
    

    /*
    public void removeCliente(java.lang.String clienteId) {
        Session session = banco.HibernateUtil.currentSession();
        org.hibernate.Query query = session.createQuery(
                " delete cliente from " +
                " Cliente as cliente " +
                " where " +
                " cliente.id = " +
                clienteId );   
    }
    */
    
    public void removeCliente(Cliente cliente) {
        Session session = banco.HibernateUtil.currentSession();
        Transaction tx = session.beginTransaction();
        session.delete(cliente);
        tx.commit();
        banco.HibernateUtil.closeSession();
    }
    
    public banco.Cliente getClienteById(java.lang.String clienteId) {
        Session session = banco.HibernateUtil.currentSession();
        org.hibernate.Query query = session.createQuery(
                " select cliente " +
                " from  " +
                " Cliente as cliente " +
                "  where  " +
                " cliente.id = ? ");
        query.setParameter(0,clienteId);
        
        return (banco.Cliente) query.uniqueResult();
    }
}
